﻿using Mangox.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Http;

namespace MGXAPI.Controllers.Test
{

    public class BaiduController : ApiController
    {

        /// <summary>
        /// http://localhost:13772/api/Baidu/test
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string test()
        {
            return "test Baidu";
        }

        /// <summary>
        /// http://localhost:13772/api/Baidu/Login
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResultBaseXCX Login(canshu obj)
        {
            ApiResultBaseXCX ret = new ApiResultBaseXCX();
            var url = "https://spapi.baidu.com/oauth/jscode2sessionkey";


            //string code = Request["code"] ?? string.Empty;
            //string resData = Request["data"] ?? string.Empty;
            //string iv = Request["iv"] ?? string.Empty;

            string code = obj.code ?? string.Empty;
            string resData = obj.data ?? string.Empty;
            string iv = obj.iv ?? string.Empty;

            string client_id = "zHGHoPO8Owz11cdtVpGZKaCuEYaOROWp";
            string sk = "CEHxzLCifyeVd7BES2h0LwsMffzz4GKz";

            string result = null;
            try
            {
                //var obj = JsonConvert.DeserializeObject<dynamic>(resData);

                var param = new { code, client_id, sk };
                result = WebRequestHelper.HttpPost(url, null, param);

                //var retModel = new { openid = "", session_key = "" };

                var retModel = JsonCommon.JsonToMode2<fanhui>(result);

                //解密
                result = AES_decrypt(resData, retModel.session_key, iv);
                //result = HttpUtility.UrlDecode(result);
                //result = DecodeBase64(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            ret.package = result;

            return ret;
        }


        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }

        /// <summary>
        /// 没有加密数据：
        /// 有加密数据：
        /// </summary>
        /// <param name="encryptedDataStr"></param>
        /// <param name="session_key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public string AES_decrypt(string encryptedDataStr, string session_key, string iv)
        {
            RijndaelManaged rijalg = new RijndaelManaged();
            //-----------------    
            //设置 cipher 格式 AES-192-CBC    

            rijalg.KeySize = 192;

            rijalg.Padding = PaddingMode.PKCS7;
            rijalg.Mode = CipherMode.CBC;

            rijalg.Key = Convert.FromBase64String(session_key);
            rijalg.IV = Convert.FromBase64String(iv);

            byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);
            //解密    
            ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);

            string result;
            using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        result = srDecrypt.ReadToEnd();
                    }
                }
            }
            return result;
        }


    }


    public class fanhui
    {
        public string openid { get; set; }
        public string session_key { get; set; }
    }
    public class canshu
    {
        public string code { get; set; }
        public string data { get; set; }
        public string iv { get; set; }
    }

    /// <summary>
    /// 数据包
    /// </summary>
    public class Package
    {
        /// <summary>
        /// 发展商ID
        /// </summary>
        public string companyid;
        /// <summary>
        /// 分销商ID
        /// </summary>
        public string channelid;

        /// <summary>
        /// 返回代码
        /// </summary>
        public string ret;
        /// <summary>
        /// 错误信息，若ret不为0时才有值
        /// </summary>
        public string err;
        /// <summary>
        /// 接口的处理类型
        /// </summary>
        /// <summary>
        /// 参数的密文或返回结果（解密后是一串JSON的字符串）
        /// </summary>
        public string package;

        /// <summary>
        /// 类名
        /// </summary>
        public string ClassName;
        /// <summary>
        /// 接口的方法名
        /// </summary>
        public string MethodName;

        /// <summary>
        /// 返回结果的明文
        /// </summary>
        public string OutputData;

        public int ApiType;

        /// <summary>
        /// 明源接口输入
        /// </summary>
        public string MingYuanInput;
        /// <summary>
        /// 明源接口输出（返回结果）
        /// </summary>
        public string MingYuanOutput;
        /// <summary>
        /// api版本
        /// </summary>
        public string appVersion = string.Empty;

        /// <summary>
        /// 用户身份验证字符串token
        /// </summary>
        public string token = string.Empty;
    }

    /// <summary>
    /// 接口的返回结果类，每个结果都返回给ApiService进行处理。
    /// </summary>
    public class ApiResultBase
    {
        public ApiResultBase()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            ret = ReturnCode.Success;
        }
        /// <summary>
        /// 接口结果代码，默认是成功
        /// </summary>
        public string ret = string.Empty;
        /// <summary>
        /// 错误信息，若ret不为0时才有值
        /// </summary>
        public string err = string.Empty;
        /// <summary>
        /// 接口的返回结果（结果为一串JSON）
        /// </summary>
        public string package = string.Empty;

        public string time = string.Empty;
    }

    /// <summary>
    /// ApiResultBaseXCX 的摘要说明
    /// </summary>
    public class ApiResultBaseXCX : ApiResultBase
    {
        public string token { set; get; }
    }

    /// <summary>
    /// <para>0	表示成功</para>
    /// <para>1	companyid或 channelid不正确</para>
    /// <para>2	解密失败，请检查您的密钥是否正确</para>
    /// <para>3	不存在的接口，请检查接口url是否正确</para>
    /// <para>4	未处理的异常</para>
    /// <para>5	package参数不正确</para>
    /// <para>101	第三方接口未处理的异常</para>
    /// <para>102	第三方接口调用失败</para>
    /// <para>1001	办理业务失败</para>
    /// </summary>
    public static class ReturnCode
    {
        /// <summary>
        /// 0 表示成功
        /// </summary>
        public static readonly string Success = "0";
        /// <summary>
        /// 1 companyid或 channelid不正确
        /// </summary>
        public static readonly string CompanyidOrChannelidErr = "1";
        /// <summary>
        /// 2 解密失败，请检查您的密钥是否正确
        /// </summary>
        public static readonly string DecryptionErr = "2";
        /// <summary>
        /// 3 链接错误
        /// </summary>
        public static readonly string LinkError = "3";
        /// <summary>
        /// 4 未处理的异常
        /// </summary>
        public static readonly string NoException = "4";
        /// <summary>
        /// 5 package参数不正确
        /// </summary>
        public static readonly string PackageErr = "5";
        /// <summary>
        /// 101 第三方接口未处理的异常
        /// </summary>
        public static readonly string TimeErr = "6";
        /// <summary>
        /// 101 第三方接口未处理的异常
        /// </summary>
        public static readonly string InterfaceUntreatedErr = "101";
        /// <summary>
        /// 102 第三方接口调用失败
        /// </summary>
        public static readonly string InterfaceErr = "102";
        /// <summary>
        /// 1001 业务的错误
        /// </summary>
        public static readonly string YeWuErr = "1001";
        /// <summary>
        /// 没有记录
        /// </summary>
        public static readonly string NoRecord = "1002";
        /// <summary>
        /// 1033 token验证失败
        /// </summary>
        public static readonly string TokenInvalid = "1033";
    }

}
